import javaagent.HelloWorld;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * @author ：zzs
 * @version : 1.0
 * @date ：Created in 2022/2/26 9:30
 * @description：
 */
public class MyDemo {

    @Test
    public void test1() throws Exception {
        ClassPool pool = new ClassPool();
        pool.appendSystemPath();
        CtClass ctClass = pool.get("javaagent.HelloWorld");
        CtMethod method = ctClass.getDeclaredMethods()[0];
        //1. 拷贝新方法
        CtMethod newMethod = CtNewMethod.copy(method, ctClass, null);
        // 2.  改个名字
        newMethod.setName(method.getName() + "$agent1");
        ctClass.addMethod(newMethod);
        // 主要的注入代码
        StringBuffer body = new StringBuffer();
        body.append("return System.currentTimeMillis();");
        newMethod.setBody(String.valueOf(body));
        ctClass.toClass();
        Files.write(new File(System.getProperty("user.dir") + "/target/hello.class").toPath(), ctClass.toBytecode());
        HelloWorld helloWorld = new HelloWorld();
        Object hello = helloWorld.getClass().getMethod("hello$agent1").invoke(helloWorld);
        System.out.println(hello);
    }

}
